package com.example.yiwei.crm.view.activity.customerActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetAreData;
import com.example.yiwei.crm.data.GetContact;
import com.example.yiwei.crm.data.GetCustumer;
import com.example.yiwei.crm.entity.BZFLEntity;
import com.example.yiwei.crm.entity.ContactMessageEntity;
import com.example.yiwei.crm.entity.CustomerMessageEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.json.YYSpinnerJson;
import com.example.yiwei.crm.json.contactJson;
import com.example.yiwei.crm.json.customerJson;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.util.ZhengZhe;
import com.example.yiwei.crm.view.activity.areActivity.ProvinceActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BaseUpdateActivity extends AppCompatActivity {
    private Spinner spinner_manager,spinner_yl;
    private EditText edit_name,edit_age,edit_id_card,edit_adress,edit_bx;
    private String pname,cname,aname,pid,cid,aid;
    private RadioGroup rg_sex;
    private RadioButton rb_men,rb_women;
    private ArrayAdapter adapter1;
    private TextView txt_adress;
    private ArrayAdapter adapter;
    List<BZFLEntity> list;
    List<String> alist;
    private ImageView img_back,img_commit;
    private String birth_time;
    String sresult;
    List<managerEntity> managerList;
    private List<String> name_list=new ArrayList<>();
    String managerName,result;
    int manager_id,sex,ylid;
    CustomerMessageEntity customer;
    ContactMessageEntity contact;
    SharedPreferences sp;
    int customer_id;
    private String ylname;
    Button showbutton;
    int c=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_update_base);
        list = new ArrayList<>();
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        txt_adress = (TextView) findViewById(R.id.customer_add_base_adress);
        spinner_yl = (Spinner) findViewById(R.id.userAdd_spinner_medical_class);
        showbutton = (Button) findViewById(R.id.customer_add_base_adress_show);
        edit_id_card= (EditText) findViewById(R.id.customer_add_edit_idcard);
        edit_adress = (EditText) findViewById(R.id.customer_add_edit_adress);
        spinner_manager= (Spinner) findViewById(R.id.customer_add_spinner_manager);
        edit_age= (EditText) findViewById(R.id.customer_add_edit_age);
        edit_name= (EditText) findViewById(R.id.customer_add_edit_name);
        edit_bx = (EditText) findViewById(R.id.userAdd_edit_security_numbers);
        rg_sex= (RadioGroup) findViewById(R.id.customer_add_rg_sex);
        rb_men= (RadioButton) findViewById(R.id.customer_add_rb_men);
        rb_women= (RadioButton) findViewById(R.id.customer_add_rb_women);
        img_back= (ImageView) findViewById(R.id.user_add_img_backb);
        img_commit= (ImageView) findViewById(R.id.userBase_btn_nextb);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }

        });
        showbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BaseUpdateActivity.this, ProvinceActivity.class);
                GetAreData.pname=null;
                GetAreData.aname = null;
                GetAreData.cname = null;
                GetAreData.pid = null;
                GetAreData.cid = null;
                GetAreData.aid = null;
                startActivity(intent);
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    object.put("admin",sp.getString("admin",null));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                String result = NetWorkUtils.getCount(baseClass.find_YLLB_URL,json);
                list = YYSpinnerJson.getYLLB(result);
                managerDao manaDao=new managerDaoImpl();
                managerList=manaDao.queryAllManager(baseClass.query_manager_url,json);
                for (int i2=0;i2<managerList.size();i2++){
                    name_list.add( managerList.get(i2).getManager_name());
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter1 = new ArrayAdapter(BaseUpdateActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, name_list);
                        adapter1.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        spinner_manager.setAdapter(adapter1);

                        spinner_manager.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                managerName=managerList.get(i).getManager_name();
                                manager_id = managerList.get(i).getManager_id();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                        alist = new ArrayList<>();
                        for (int i =0;i<list.size();i++){
                            alist.add(list.get(i).getName());
                        }
                        adapter = new ArrayAdapter(BaseUpdateActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, alist);
                        adapter.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        spinner_yl.setAdapter(adapter);
                        spinner_yl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                ylname = list.get(position).getName();
                                ylid = list.get(position).getId();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        setMessage();
                    }
                });
            }
        }).start();
        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i==rb_men.getId()){
                    sex=1;
                }else{
                    sex=2;
                }
            }
        });
        img_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean b = ZhengZhe.idCard(edit_id_card.getText().toString());
                if ("".equals(edit_name.getText().toString())||"".equals(edit_age.getText().toString())) {

                    Toast.makeText(BaseUpdateActivity.this, "请填写必填项!", Toast.LENGTH_SHORT).show();
                }else if("".equals(txt_adress.getText().toString())){
                    Toast.makeText(BaseUpdateActivity.this, "请选择行政区域!", Toast.LENGTH_SHORT).show();
                }else if(!"".equals(edit_id_card.getText().toString())&&!b){
                    Toast.makeText(BaseUpdateActivity.this, "请填写正确的身份证号!", Toast.LENGTH_SHORT).show();
                }else  {
                    add();
                }
            }
        });

    }
    public void setMessage(){
        customer = GetCustumer.get();
        contact = GetContact.get();
        for (int i = 0;i<name_list.size();i++){
            if (name_list.get(i).equals(customer.getClient_manager_name())){
                spinner_manager.setSelection(i);
            }
        }
        for (int i= 0;i<list.size();i++){
            if (list.get(i).getId()==customer.getMedical_class_id()){
                spinner_yl.setSelection(i);
            }
        }
        edit_bx.setText(customer.getSecurity_numbers());
        edit_name.setText(customer.getClient_name());
        edit_id_card.setText(customer.getIDNumber());
        edit_adress.setText(customer.getClient_Address());
        edit_age.setText(customer.getClient_age()+"");
        txt_adress.setText(customer.getPname()+customer.getCname()+customer.getAname());
        if (customer.getClient_gender() != 0) {
            if (customer.getClient_gender() == 1) {
                rb_men.setChecked(true);
            } else if (customer.getClient_gender() == 2) {
                rb_women.setChecked(true);
            }
        }
    }
    public void add() {
            img_commit.setVisibility(View.GONE);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SC sc = new SC();
                    JSONObject json = sc.storage(sp);
                    try {
                        json.put("KAA02", edit_name.getText().toString());
                        json.put("KAA03", edit_age.getText().toString());
                        if (rb_men.isChecked()) {
                            json.put("KAA04", 1);
                        } else if (rb_women.isChecked()) {
                            json.put("KAA04", 2);
                        }
                        json.put("KAA07", edit_id_card.getText().toString());
                        json.put("KAA08", edit_adress.getText().toString());
                        json.put("KAA09", manager_id);
                        json.put("KAA09A", managerName);
                        json.put("addoredit", "edit");
                        json.put("AKE01",ylid);
                        json.put("KAA12",edit_bx.getText().toString());
                        json.put("KAA01", customer.getClient_id());
                        if (pid != null) {
                            json.put("KAA23", Integer.valueOf(pid));
                            json.put("KAA24", Integer.valueOf(cid));
                            json.put("KAA25", Integer.valueOf(aid));
                            json.put("KAA30", pname);
                            json.put("KAA31", cname);
                            json.put("KAA32", aname);
                        }
                        json.put("CID03", sp.getString("CID03", null));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    String sjson = json.toString();
                    //新增客户信息
                    sresult = NetWorkUtils.getCount(baseClass.add_coor_customer_URL, sjson);
                    Log.d("cc", sresult);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (sresult != null) {
                                try {
                                    JSONObject object = new JSONObject(sresult);
                                    boolean b = object.getBoolean("ifsuccess");
                                    if (b) {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                JSONObject object1 = new JSONObject();
                                                try {
                                                    object1.put("KAA01",customer.getClient_id());
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                                GetCustumer.create();
                                                GetContact.create();
                                                String json = object1.toString();
                                                String reult = NetWorkUtils.getCount(baseClass.find_customer_msg, json);
                                                GetCustumer.customers = customerJson.jsonCustomerDetailedMessage1(reult,null);
                                                GetContact.contact = contactJson.detailedContactMessageJson1(reult,null);
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (GetCustumer.customers!=null&& GetContact.contact!=null){
                                                            finish();
                                                        }

                                                    }
                                                });
                                            }
                                        }).start();
                                    } else {
                                        img_commit.setVisibility(View.VISIBLE);
                                        Toast.makeText(BaseUpdateActivity.this, "更新客户客户失败", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                }
            }).start();


        }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        if (GetAreData.pname!=null){
            pid = GetAreData.pid;
            pname = GetAreData.pname;
            cid = GetAreData.cid;
            cname = GetAreData.cname;
            aid = GetAreData.aid;
            aname =GetAreData.aname;
            txt_adress.setText(pname+cname+aname);
        }
    }
}
